<template>
	<div class="operation mb15">
		<span>
			告警级别：
			<el-select v-model="alarmInfo.params.ruleLevel" @change="handleRuleLevelChange" class="width-150">
				<el-option
					v-for="item in ruleLevelOptions"
					:key="item.value"
					:label="item.label"
					:value="item.value"
				/>
			</el-select>
		</span>
		<span>
			<el-button type="primary" @click="resetRule" :disabled="selectRowId==null">重置</el-button>
			<el-button type="primary" @click="editRule" :disabled="selectRowId==null">编辑</el-button>
			<el-button type="primary" @click="getAlarmStrategyList">刷新</el-button>
		</span>
	</div>
	<el-table
		ref="tableRef"
		border
		:data="alarmInfo.data"
		element-loading-text="数据加载中..."
		highlight-current-row
		row-key="nodeId"
		height="calc(100vh - 505px)"
		@row-click="handleRowClick"
	>
		<el-table-column prop="ruleName" label="告警指标" min-width="130" show-overflow-tooltip />
		<el-table-column prop="ruleModule" label="告警模块"  min-width="100" show-overflow-tooltip />
		<el-table-column label="告警级别" min-width="100" show-overflow-tooltip>
			<template v-slot="{ row }">
				<span>
					{{ruleLevelMap[row.ruleLevel]}}
				</span>
			</template>
		</el-table-column>
		<el-table-column prop="ruleThreshold" label="告警阈值" min-width="130" show-overflow-tooltip>
			<template v-slot="{ row }">
				<span v-if="disabledInputArr.includes(row.ruleName)">
					{{ ['0','1','2'].includes(row.ruleThreshold) ? alarmMap[row.ruleThreshold] : row.ruleThreshold }}
				</span>
				<span v-else>
					{{ row.ruleThreshold }}
				</span>
			</template>
		</el-table-column>
		<el-table-column prop="ruleTimes" label="持续时间(分钟)" min-width="130" show-overflow-tooltip />
	</el-table>
	<el-pagination
		v-model:current-page="alarmInfo.params.pageNum"
		v-model:page-size="alarmInfo.params.pageSize"
		@current-change="onHandleCurrentChange"
		@size-change="onHandleSizeChange"
		class="mt15"
		:pager-count="5"
		:page-sizes="[10, 20, 30, 50]"
		background
		layout="total, sizes, prev, pager, next, jumper"
		:total="alarmInfo.total"
	>
	</el-pagination>

	<el-dialog :destroy-on-close="true" width="500px" v-model="editStrategyVisible" title="告警策略设置">
		<el-form ref="editRuleRef" :rules="editAlarmRules" :model="editAlarmData" label-width="100px">
			<el-form-item :label="`告警阈值${unit}:`" prop="ruleThreshold">
				<el-input v-model="editAlarmData.ruleThreshold" style="width:90%" :disabled="disabledInput"/>
			</el-form-item>
			<el-form-item label="持续时间(分):" prop="ruleTimes">
				<el-input v-model="editAlarmData.ruleTimes" style="width:90%" />
			</el-form-item>
			<el-form-item label="告警级别:">
				<el-select v-model="editAlarmData.ruleLevel" style="width:90%">
					<el-option v-for="level in ruleLevelOptions.filter(item => item.value!==null)" :key="level.value" :value="level.value" :label="level.label">{{level.label}}</el-option>
				</el-select>
			</el-form-item>
		</el-form>
		<template #footer>
			<el-button @click="editStrategyVisible=false">取消</el-button>
			<el-button type="primary" @click="handleEditRule(editRuleRef)">确定</el-button>
		</template>
	</el-dialog>
</template>

<script setup lang="ts">
import { computed, reactive, ref, toRefs } from 'vue';
import { AlarmStrategStateInterface } from '../interface/index';
import { ElMessage, ElMessageBox } from 'element-plus';
import type { FormInstance } from 'element-plus';
import { useAlarmApi } from '/@/api/alarm';
import { alarmMap } from '/@/utils/const';

const alarmApi = useAlarmApi();
const ruleLevelOptions = [
	{
		label: '全部',
		value: null
	},
	{
		label: '提示',
		value: 0
	},
	{
		label: '一般',
		value: 1
	},
	{
		label: '重要',
		value: 2
	},
	{
		label: '紧急',
		value: 3
	},
];
const ruleLevelMap:{
	[key:string]:string
} = {
	'0': '提示',
	'1': '一般',
	'2': '重要',
	'3': '紧急',
};
let state = reactive<AlarmStrategStateInterface>({
	alarmInfo: {
		data: [],
		params: {
			pageSize: 10,
			pageNum: 1,
			ruleLevel: null
		},
		total: 0
	},
	editAlarmData: {
		ruleThreshold: null,
		ruleTimes: null,
		ruleLevel: null,
		ruleId: null
	}
});

let { alarmInfo, editAlarmData } = toRefs(state);

const getAlarmStrategyList = () => {
	alarmApi.getAlarmStrategyList({
		pageNo: state.alarmInfo.params.pageNum,
		pageSize: state.alarmInfo.params.pageSize,
		ruleLevel: state.alarmInfo.params.ruleLevel
	}).then(res => {
		alarmInfo.value.data = res.data.records;
		alarmInfo.value.total = res.data.total;
		selectRowId.value = null;
	});
};
getAlarmStrategyList();

let selectRowId = ref<null | number>(null);
let selectRow = ref<any>();
const handleRowClick = (row:any) => {
	selectRowId.value = row.id;
	selectRow.value = row;
};

const onHandleCurrentChange = (val:any) => {
	alarmInfo.value.params.pageNum = val;
	getAlarmStrategyList();
};
const onHandleSizeChange = (val:any) => {
	alarmInfo.value.params.pageSize = val;
	getAlarmStrategyList();
};

const editRuleRef = ref<FormInstance>();
const validateRuleThreshold = (rule: any, value: any, callback: any) => {
	if (value === '') {
		return callback(new Error('请输入告警阈值'));
	}
	var reg = /^\d*(\.\d+)?$/;
	if (!reg.test(value)) {
		return callback(new Error('告警阈值格式应为正数'));
	}
	callback();
};
const validateRuleTimes = (rule: any, value: any, callback: any) => {
	if (value === '') {
		return callback(new Error('请输入告警持续时间'));
	}
	var reg = /^[1-9]\d*$/;
	if (!reg.test(value)) {
		return callback(new Error('告警持续时间格式应为正整数'));
	}
	callback();
};
const editAlarmRules = reactive({
	ruleThreshold: [{ validator: validateRuleThreshold, trigger: 'blur' }],
	ruleTimes: [{ validator: validateRuleTimes, trigger: 'blur' }]
});

// edit
const unit = computed(() => {
	let regex = new RegExp(/[\(\（](.*?)[\)\）]/g);
	let res = '';
	if (selectRow.value) {
		res = selectRow?.value.ruleName?.match(regex) && selectRow?.value.ruleName.match(regex)[0];
	}
	return res || '';
});
let editStrategyVisible = ref(false);
const disabledInputArr = ['集群状态告警', '集群状态异常', 'OSDs响应速率'];
const disabledInput = ref(false);
const editRule = () => {
	disabledInput.value = disabledInputArr.includes(selectRow.value.ruleName);
	getAlarmInfoById().then((data:any) => {
		editStrategyVisible.value = true;
		const { ruleThreshold, ruleLevel, ruleTimes, id } = data;
		editAlarmData.value = {
			ruleThreshold: disabledInputArr.includes(selectRow.value.ruleName) ? (['0', '1', '2'].includes(ruleThreshold) ? alarmMap[ruleThreshold] : ruleThreshold) : selectRow.value.ruleThreshold,
			ruleLevel,
			ruleTimes: Number(ruleTimes),
			ruleId: id };
	});
};
const handleEditRule = (formEl: FormInstance | undefined) => {
	let req = JSON.parse(JSON.stringify(editAlarmData.value));

	if (!formEl) return;

	if (disabledInputArr.includes(selectRow.value.ruleName)) {
		req.ruleThreshold = selectRow.value.ruleThreshold;
		editAlarmRules.ruleThreshold.pop();
	} else {
		if (editAlarmRules.ruleThreshold.length < 1) {
			editAlarmRules.ruleThreshold.push({ validator: validateRuleThreshold, trigger: 'blur' });
		}
	}

	formEl.validate((valid) => {
		if (!valid) return;
		alarmApi.updateAlarmStrategy(req).then(() => {
			ElMessage.success('编辑告警策略成功!');
			getAlarmStrategyList();
			editStrategyVisible.value = false;
		});
	});
};

const getAlarmInfoById = () => {
	return new Promise((resolve) => {
		alarmApi.getAlarmStrategy(selectRowId.value).then(res => {
			resolve(res.data);
		});
	});
};

const resetRule = () => {
	getAlarmInfoById().then((data:any) => {
		ElMessageBox.confirm(`确认重置${data.ruleName}告警指标?`, '重置告警设置', {
			cancelButtonText: '取消',
			confirmButtonText: '确定',
			type: 'warning'
		}).then(() => {
			alarmApi.resetAlarmStrategy(data.id).then(() => {
				ElMessage.success('重置成功！');
				getAlarmStrategyList();
			});
		});
	});
};
const handleRuleLevelChange = (val:any) => {
	alarmInfo.value.params.ruleLevel = val;
	getAlarmStrategyList();
};

</script>